package com.auto.qinglong.ui.viewmodel

import androidx.lifecycle.viewModelScope
import com.auto.base.net.ResultWrapper
import com.auto.base.ui.BaseViewModel
import com.auto.qinglong.net.client.QlRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import javax.inject.Inject

data class LogUiState(val logStr: String = "")

data class LogViewModelState(val logStr: String = "") {
    fun toUiState(): LogUiState = LogUiState(logStr)
}


@HiltViewModel
class TaskLogViewModel @Inject constructor(val qlRepository: QlRepository) : BaseViewModel() {
    private val viewModelState = MutableStateFlow(
        LogViewModelState()
    )
    val uiState = viewModelState.map(LogViewModelState::toUiState)
        .stateIn(viewModelScope, SharingStarted.Eagerly, viewModelState.value.toUiState())

    private var pollingJob: Job? = null

    private val _scrollToBottomEvent = MutableSharedFlow<Unit>()
    val scrollToBottomEvent: SharedFlow<Unit> = _scrollToBottomEvent

    fun checkLog(taskId: String) {
        // 避免重复调用
        if (pollingJob?.isActive == true) return
        pollingJob = viewModelScope.launch {
            var isFirst = true
            while (isActive) {
                try {
                    val result = qlRepository.getTaskLog(taskId)
                    var over = false
                    when (result) {
                        is ResultWrapper.Success -> {
                            result.data?.let { log ->
                                viewModelState.update {
                                    it.copy(log)
                                }

                                val lastLog = log.trim()
                                    .lines()
                                    .lastOrNull()
                                over = lastLog?.contains("##执行结束") == true
                                if (!isFirst) {
                                    // ✅ 发出滚动到底部事件
                                    _scrollToBottomEvent.emit(Unit)
                                }
                                isFirst = false
                            }
                        }

                        is ResultWrapper.Error -> {
                            result.exception.message?.let { showToast(it) }
                        }
                    }
                    if (over) break  // 请求成功，停止轮询

                    delay(1000L)  // 等待1秒再次请求
                } catch (e: Exception) {
                    e.message?.let { showToast(it) }
                    break
                }
            }
        }
    }
}